package cc.rengu.redp.common.pwdsecruity;

import cc.rengu.redp.common.utils.EncryptUtil;
import cc.rengu.redp.common.utils.gmhelper.SM4Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component("gmPasswordEncryptor")
public class GmPasswordEncryptor implements StringEncryptor {

    @Value("${redp.launchKey:}")
    private String launchKey;

    @Override
    public String encrypt(String s) {
        return null;
    }

    @Override
    public String decrypt(String s) {
        if (StringUtils.isBlank(launchKey)) {
            log.error("[GmPasswordEncryptor] lack of launchKey");
            return null;
        }

        String iv = (new StringBuilder(launchKey)).reverse().toString();
        try {
            String rs =  new String(SM4Util.decrypt_CBC_Padding(launchKey.getBytes(), iv.getBytes(), EncryptUtil.hexStr2ByteArr(s)));
            return rs;
        } catch (Exception e) {
            log.error("[GmPasswordEncryptor] decrypt configuration error.", e);
        }
        return null;
    }
}
